package com.imjohn.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.UUID;

public class jwtUtil {
    private static long time = 1000*60*30;
    private static String signature = "imjohn";
    /*生成token*/
    public static String createToken(String name, HttpServletRequest param) {
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwttoken = jwtBuilder
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .claim("username", name)
                .claim("role", "admin")
                .setSubject("admin-test")
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256, signature)
                .compact();
        /*session操作*/
        HttpSession session = param.getSession();
        session.setAttribute("token", jwttoken);
        return jwttoken;
    }
    /*检查token*/
    public static boolean checkJwtToken(String param) {
        if (StringUtils.isEmpty(param)) return false;
        try {
            Jwts.parser().setSigningKey(signature).parseClaimsJws(param);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }
    /*获取token信息*/
    public static String getInfoByJwtToken( HttpServletRequest request ){
        String jwtToekn = request.getHeader("X-Token");
        System.out.println("jwtToken:" + jwtToekn);
        if (StringUtils.isEmpty(jwtToekn)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(signature).parseClaimsJws(jwtToekn);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("role");

    }
}
